﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WCSY.MODEL;
using WCSY.BLL;
using System.Data;

public partial class CostsManagement_costsApplyOrder : System.Web.UI.Page
{
    Fg_deptInfoManager deptM = new Fg_deptInfoManager();
    Fg_empInfoManager empM = new Fg_empInfoManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //如果不为Null,则为修改状态
            if (Request["sysno"] != null)
            {
                //初始化主表信息
                wcsy_costsOrderMstManager mstm = new wcsy_costsOrderMstManager();
                string sysno = Request["sysno"].ToString();
                this.txtsysno.Text = sysno;
                DataTable mstdt = mstm.GetAllListByPara(sysno, "-1", "", "", "", "").Tables[0];
                this.txtfilldate.Text = Convert.ToDateTime(mstdt.Rows[0]["filldate"]).ToShortDateString();
                //绑定申请部门
                DataTable deptList = deptM.GetAllList().Tables[0];
                this.ddlapplyDept.DataSource = deptList;
                this.ddlapplyDept.DataTextField = "deptname";
                this.ddlapplyDept.DataValueField = "id";
                this.ddlapplyDept.DataBind();
                this.ddlapplyDept.SelectedValue = mstdt.Rows[0]["applydept"].ToString();
                //绑定申请人
                string deptno = ddlapplyDept.SelectedValue;
                DataSet empList = empM.GetList(" DeptNo = '"+deptno+"'");
                this.ddlapplyPsn.DataSource = empList;
                this.ddlapplyPsn.DataTextField = "empname";
                this.ddlapplyPsn.DataValueField = "id";
                this.ddlapplyPsn.DataBind();
                this.ddlapplyPsn.SelectedValue = mstdt.Rows[0]["applypsn"].ToString();
                //绑定费用使用日期
                this.txtcostOfDateB.Text = Convert.ToDateTime(mstdt.Rows[0]["costofdateb"]).ToShortDateString();
                this.txtcostOfDateE.Text = Convert.ToDateTime(mstdt.Rows[0]["costofdatee"]).ToShortDateString();
                //费用用途
                this.txtcostUse.Text = mstdt.Rows[0]["costuse"].ToString();
                //备注
                this.txtremarks.Text = mstdt.Rows[0]["remarks"].ToString();
                //制单人
                this.lblfillpsn.Text = mstdt.Rows[0]["fillpsn"].ToString();
                //合计
                this.lblSumAppMoney.Text = mstdt.Rows[0]["locsum"].ToString();

                //绑定明细表
                wcsy_costsOrderDetManager detm = new wcsy_costsOrderDetManager();
                DataTable detdt = detm.GetList(" sysno = '"+sysno+"'").Tables[0];
                this.HiddenField1.Value = detdt.Rows.Count.ToString();
                for (int i = 1; i <= 30;i++ )
                {
                    DataRow dr = detdt.NewRow();
                    dr["lineid"] = i + Convert.ToInt32(this.HiddenField1.Value);
                    detdt.Rows.Add(dr);
                }
                this.costorderdetRepeater.DataSource = detdt;
                this.costorderdetRepeater.DataBind();

                tool.SetControlReadOnly(this);
                this.btnSave.Visible = false;
            }
            else
            {
                //初始化主表信息
                this.txtsysno.Text = tool.GetMaxSysno("sysno", "wcsy_costsordermst");
                this.txtfilldate.Text = DateTime.Now.Date.ToShortDateString();
                //设置费用使用日期
                this.txtcostOfDateB.Text = DateTime.Now.Date.ToShortDateString();
                this.txtcostOfDateE.Text = DateTime.Now.Date.ToShortDateString();
                //绑定申请部门
                DataTable deptList = deptM.GetAllList().Tables[0];
                this.ddlapplyDept.DataSource = deptList;
                this.ddlapplyDept.DataTextField = "deptname";
                this.ddlapplyDept.DataValueField = "id";
                this.ddlapplyDept.DataBind();

                if (Session["userName"] == null)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>chkLogin();</script>");
                }
                else
                {

                    string userId = Session["userId"].ToString();
                    //根据userId 获取操作员所在部门,默认设置申请部门

                   DataTable deptls = empM.GetList(" empno='" + userId + "'").Tables[0];
                    if (deptls.Rows.Count > 0)
                    {
                        string depno = deptls.Rows[0]["deptno"].ToString();
                        this.ddlapplyDept.SelectedValue = depno;

                    }
                    //绑定制单人
                    this.lblfillpsn.Text = Session["userName"].ToString();

                }
                //绑定申请人
                string deptno = ddlapplyDept.SelectedValue;
                DataSet empList = empM.GetList(" DeptNo = '" + deptno + "'");
                this.ddlapplyPsn.DataSource = empList;
                this.ddlapplyPsn.DataTextField = "empname";
                this.ddlapplyPsn.DataValueField = "id";
                this.ddlapplyPsn.DataBind();

                //初始化明细表
                List<wcsy_costsOrderDet> detlist = tool.GetOrderDetData();
                this.costorderdetRepeater.DataSource = detlist;
                this.costorderdetRepeater.DataBind();
            }
        }
    }
    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //修改状态
        if (Request["sysno"] != null)
        {
            List<string> sqlList = new List<string>();
            wcsy_costsOrderMstManager mstm = new wcsy_costsOrderMstManager();
            #region 保存主表数据
            try
            {
                //如果单据修改，（则重新获取当前预算执行期间 还是使用原预算执行期间，待讨论，这里使用重新获取）
                fg_InitialBuMstManager bum = new fg_InitialBuMstManager();
                DataTable nowbuDt = bum.getNowBu();
                wcsy_costsOrderMst mst = new wcsy_costsOrderMst();
                mst.sysno = Request["sysno"].ToString();
                mst.applyPsn = ddlapplyPsn.SelectedValue;
                mst.applyDept = ddlapplyDept.SelectedValue;
                mst.costOfDateB = Convert.ToDateTime(txtcostOfDateB.Text).Date;
                mst.costOfDateE = Convert.ToDateTime(txtcostOfDateE.Text).Date;
                mst.costUse = txtcostUse.Text;
                mst.remarks = txtremarks.Text;
                mst.fillpsn = lblfillpsn.Text;
                mst.filldate = DateTime.Now.Date;
                
                if (nowbuDt.Rows.Count > 0)
                {
                    mst.buSysno = nowbuDt.Rows[0]["sysno"].ToString();
                }
                else
                {
                    throw new Exception("未获取到当前预算执行期间，请先进行预算执行！");
                }
                sqlList.Add(mstm.Update(mst));
            }
            catch (Exception ex)
            {
                tool.Alert("修改失败！" + ex.Message, this);
                return;
            }
            #endregion
            #region 保存明细表数据
            try
            {
                wcsy_costsOrderDetManager detm = new wcsy_costsOrderDetManager();
                sqlList.Add(detm.Delete(Request["sysno"].ToString()));
                wcsy_costsOrderDet det = null;
                for (int i = 0; i < Convert.ToInt32(this.HiddenField1.Value); i++)
                {
                    det = new wcsy_costsOrderDet();
                    det.sysno = Request["sysno"].ToString();
                    det.lineid = i + 1;
                    det.costsName = (costorderdetRepeater.Items[i].FindControl("ddlcostsName") as DropDownList).SelectedValue;
                    if (det.costsName.Equals("-1"))
                    {
                        continue;
                    }
                    
                    det.applyMoney = Convert.ToDecimal((costorderdetRepeater.Items[i].FindControl("txtapplyMoney") as TextBox).Text.Equals("") ?
                        "0" : (costorderdetRepeater.Items[i].FindControl("txtapplyMoney") as TextBox).Text);
                    det.remarks = (costorderdetRepeater.Items[i].FindControl("txtdetremarks") as TextBox).Text;
                    sqlList.Add(detm.Add(det));

                }

            }
            catch (Exception ex)
            {

                tool.Alert("修改失败！" + ex.Message, this);
                return;
            }
            try
            {
                string suc = tool.executeSqlTran(sqlList);
                if (!suc.Equals("suc"))
                {
                    throw new Exception(suc);
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
                error = error.Replace("\r\n", "");
                error = error.Replace("\n", "");
                error = error.Replace("\r", "");
                error = error.Replace("'", "");
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", "alert('信息修改失败!" + error + "')", true);
                return;
            }
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", "alert('信息修改成功!');", true);
            //top.location.href='costsApplyOrderList.aspx'
            #endregion
        }
        else
        {
            //新增操作状态

            string sysno = tool.GetMaxSysno("sysno", "wcsy_costsordermst");
            List<string> sqlList = new List<string>();
           

            wcsy_costsOrderMstManager mstm = new wcsy_costsOrderMstManager();
            #region 保存主表数据
            try
            {
                //获取当前预算执行期间
                fg_InitialBuMstManager bum = new fg_InitialBuMstManager();
                DataTable nowbuDt = bum.getNowBu();
                wcsy_costsOrderMst mst = new wcsy_costsOrderMst();
                mst.sysno = sysno;
                mst.applyPsn = ddlapplyPsn.SelectedValue;
                mst.applyDept = ddlapplyDept.SelectedValue;
                mst.costOfDateB = Convert.ToDateTime(txtcostOfDateB.Text).Date;
                mst.costOfDateE = Convert.ToDateTime(txtcostOfDateE.Text).Date;
                mst.costUse = txtcostUse.Text;
                mst.remarks = txtremarks.Text;
                mst.fillpsn = lblfillpsn.Text;
                mst.filldate = DateTime.Now.Date;
                if (nowbuDt.Rows.Count > 0)
                {
                    mst.buSysno = nowbuDt.Rows[0]["sysno"].ToString();
                }
                else {
                    throw new Exception("未获取到当前预算执行期间，请先进行预算执行！");
                }
                sqlList.Add(mstm.Add(mst));
            }
            catch (Exception ex)
            {
                tool.Alert("保存失败！" + ex.Message, this);
                return;
            }
            #endregion
            #region 保存明细表数据
            try
            {
                wcsy_costsOrderDetManager detm = new wcsy_costsOrderDetManager();
                wcsy_costsOrderDet det = null;
                //处理单据数据，汇总部门费用项总申请金额，需要与预算值比较，看是否超出预算值
                DataTable orderBuDt = new DataTable();
                orderBuDt.Columns.Add("deptno");
                orderBuDt.Columns.Add("costsno");
                orderBuDt.Columns.Add("bumoney");
                for (int i = 0; i < Convert.ToInt32(this.HiddenField1.Value); i++)
                {
                    det = new wcsy_costsOrderDet();
                    det.sysno = sysno;
                    det.lineid = i + 1;
                    det.costsName = (costorderdetRepeater.Items[i].FindControl("ddlcostsName") as DropDownList).SelectedValue;
                    if (det.costsName.Equals("-1"))
                    {
                        continue;
                    }
                    //校验是否数字
                    //string applyMoney = (costorderdetRepeater.Items[i].FindControl("txtapplyMoney") as TextBox).Text;
                    //bool a = tool.IsNumber(applyMoney, 32, 4);
                    //return;
                    det.applyMoney = Convert.ToDecimal((costorderdetRepeater.Items[i].FindControl("txtapplyMoney") as TextBox).Text.Equals("") ?
                        "0" : (costorderdetRepeater.Items[i].FindControl("txtapplyMoney") as TextBox).Text);
                    det.remarks = (costorderdetRepeater.Items[i].FindControl("txtdetremarks") as TextBox).Text;
                    DataRow dr = orderBuDt.NewRow();
                    dr["deptno"] = ddlapplyDept.SelectedValue;
                    dr["costsno"] = det.costsName;
                    dr["bumoney"] = det.applyMoney;
                    orderBuDt.Rows.Add(dr);
                    sqlList.Add(detm.Add(det));

                }
                //费用单据申请金额
                DataTable groupdt = GetGroupTable(orderBuDt);
                //预算金额
                fg_InitialBuMstManager bum = new fg_InitialBuMstManager();
                
                for (int i = 0; i < groupdt.Rows.Count;i++ )
                {
                    //预算金额
                    DataTable budt = bum.getBuMoney(groupdt.Rows[i]["deptno"].ToString(), groupdt.Rows[i]["costsno"].ToString());
                    //数据库中，已保存数据金额
                    decimal hasApplyMoney = bum.getSumApplyMoney(groupdt.Rows[i]["deptno"].ToString(), groupdt.Rows[i]["costsno"].ToString());
                    if (budt.Rows.Count > 0)
                    {
                        //单据金额
                        decimal orderMoney = Convert.ToDecimal(groupdt.Rows[i]["bumoney"].ToString());
                        decimal sumHasMoney = hasApplyMoney + orderMoney;
                        //预算金额
                        decimal buMoney = Convert.ToDecimal(budt.Rows[0]["bumoney"].ToString());
                        if (sumHasMoney > buMoney)
                        {
                            tool.Alert("保存失败！部门费用项申请金额已超出部门预算金额，费用项" + groupdt.Rows[i]["costsno"].ToString() + "预算金额为" + buMoney.ToString() + "", this);
                            return;
                        }
                    }
                    else {
                        tool.Alert("保存失败！部门费用项" + groupdt.Rows[i]["costsno"].ToString() + " 预算金额为0", this);
                        return;
                    }
                }

            }
            catch (Exception ex)
            {

                tool.Alert("保存失败！" + ex.Message, this);
                return;
            }
            try
            {
                string suc = tool.executeSqlTran(sqlList);
                if (!suc.Equals("suc"))
                {
                    throw new Exception(suc);
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
                error = error.Replace("\r\n", "");
                error = error.Replace("\n", "");
                error = error.Replace("\r", "");
                error = error.Replace("'", "");
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", "alert('信息保存失败!" + error + "')", true);
                return;
            }
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", "alert('信息保存成功!');", true);
            //top.location.href='costsApplyOrderList.aspx'
            #endregion
        }
    }
    /// <summary>
    /// 修改时绑定repeaater droplist
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void costorderdetRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if(Request["sysno"]!=null){
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            DropDownList ddlcostsName = e.Item.FindControl("ddlcostsName") as DropDownList;
            int lineid = Convert.ToInt32((e.Item.FindControl("txtLineId") as Label).Text);
            wcsy_costsOrderDetManager detm = new wcsy_costsOrderDetManager();
            wcsy_costsOrderDet det = detm.GetMODEL(Request["sysno"].ToString(), lineid);
            if(det!=null){
                ddlcostsName.SelectedValue = det.costsName;
            }
            
            //ddlcostsName.DataSource = Fg_objManager.GetAllFg_objs();
            //ddlcostsName.DataTextField = "objName";
            //ddlcostsName.DataValueField = "objNo";
            //txtObject.DataBind();
        }
        }
    }
    //取消控件只读，并将保存按钮显现
    protected void btnUpd_Click(object sender, EventArgs e)
    {
        tool.SetControlReadOnlyNone(this);
        btnSave.Visible = true;
        btnUpd.Visible = false;
    }
    public DataTable GetGroupTable(DataTable dt)
    {
        DataView dv = dt.DefaultView;
        dv.Sort = "deptno,costsno Asc";
         dt = dv.ToTable();
        DataTable dtLwolf = dt.Clone();
        for (int i = 0; i < dt.Rows.Count; )
        {
            DataRow dr = dtLwolf.NewRow();
            string deptno = dt.Rows[i]["deptno"].ToString();
            dr["deptno"] = deptno;
            string costsno = dt.Rows[i]["costsno"].ToString();
            dr["costsno"] = costsno;

            int bumoney = 0;
            //内层也是循环同一个表，当遇到不同的name时跳出内层循环
            for (; i < dt.Rows.Count; )
            {
                if (deptno == dt.Rows[i]["deptno"].ToString() && costsno == dt.Rows[i]["costsno"].ToString())
                {
                    bumoney += Convert.ToInt32(dt.Rows[i]["bumoney"]);
                    dr["bumoney"] = bumoney;
                    i++;
                }
                else
                {
                    break;
                }
            }
            dtLwolf.Rows.Add(dr);
        }
        return dtLwolf;
    }
    //绑定申请人
    protected void ddlapplyDept_SelectedIndexChanged(object sender, EventArgs e)
    {
        //绑定申请人
        string deptno = ddlapplyDept.SelectedValue;
        DataSet empList = empM.GetList(" DeptNo = '" + deptno + "'");
        this.ddlapplyPsn.DataSource = empList;
        this.ddlapplyPsn.DataTextField = "empname";
        this.ddlapplyPsn.DataValueField = "id";
        this.ddlapplyPsn.DataBind();
    }
    //审批单据
    protected void btnApprov_Click(object sender, EventArgs e)
    {
        List<string> sqlList = new List<string>();
        try
        {
            string checkinfo = txtcheckInfo.Text;
            int checkflag = 1;
            string billno = txtsysno.Text;
            string approvpsn = tool.getRoleIdByUserId(Session["userId"].ToString());
            fg_approveObjDetAppManager approvdetm = new fg_approveObjDetAppManager();
            sqlList.Add(approvdetm.updApprovState(checkinfo,checkflag,billno,approvpsn));
        }catch(Exception ex){
            tool.Alert("审批失败！"+ex.Message,this);
            return;
        }

        try
        {
            string suc = tool.executeSqlTran(sqlList);
            if (!suc.Equals("suc"))
            {
                throw new Exception(suc);

            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
            error = error.Replace("\r\n", "");
            error = error.Replace("\n", "");
            error = error.Replace("\r", "");
            error = error.Replace("'", "");
            this.RegisterStartupScript("alert", "<script>alert('审批失败！" + error + "')</script>");
            return;

        }
        this.RegisterStartupScript("alert", "<script>alert('审批成功！')</script>");


    }
    //驳回操作
    protected void btnNoApprov_Click(object sender, EventArgs e)
    {
        List<string> sqlList = new List<string>();
        try
        {
            string checkinfo = txtcheckInfo.Text;
            int checkflag = 2;
            string billno = txtsysno.Text;
            string approvpsn = tool.getRoleIdByUserId(Session["userId"].ToString());
            fg_approveObjDetAppManager approvdetm = new fg_approveObjDetAppManager();
            sqlList.Add(approvdetm.updApprovState(checkinfo, checkflag, billno, approvpsn));
            sqlList.Add(approvdetm.delApprovState(checkinfo, checkflag, billno, approvpsn));
        }
        catch (Exception ex)
        {
            tool.Alert("驳回失败！" + ex.Message, this);
            return;
        }

        try
        {
            string suc = tool.executeSqlTran(sqlList);
            if (!suc.Equals("suc"))
            {
                throw new Exception(suc);

            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
            error = error.Replace("\r\n", "");
            error = error.Replace("\n", "");
            error = error.Replace("\r", "");
            error = error.Replace("'", "");
            this.RegisterStartupScript("alert", "<script>alert('驳回失败！" + error + "')</script>");
            return;

        }
        this.RegisterStartupScript("alert", "<script>alert('已驳回！')</script>");
    }
}
